package com.base.components.task.configuration;

import com.base.components.common.boot.event.ProcessKillForcedShutdownEvent;
import com.base.components.task.service.TaskManager;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

/**
 * TaskProcessKillForcedShutdownEvent
 *
 * @author <a href="drakelee1221@gmail.com">LiGeng</a>
 * @version v1.0.0
 * @date 2018-07-30 12:59
 */
@Component
@RefreshScope
public class TaskDestroyProcessKillForcedShutdownEvent extends ProcessKillForcedShutdownEvent implements
  ApplicationListener<ContextClosedEvent> {

  private volatile boolean onEvent;

  @Override
  public Object onEvent(ApplicationContext applicationContext) {
    Object returnObj = null;
    if(!onEvent){
      onEvent = true;
      try {
        taskDestroy(applicationContext);
      } finally {
        returnObj = super.onEvent(applicationContext);
      }
    }
    return returnObj;
  }

  @Override
  public void onApplicationEvent(@NonNull ContextClosedEvent event) {
    if(!onEvent) {
      onEvent = true;
      taskDestroy(event.getApplicationContext());
    }
  }

  /**该操作会在 SchedulerFactoryBean 销毁之前执行，可以确保关闭时所有任务执行完成；*/
  private void taskDestroy(ApplicationContext applicationContext){
    TaskManager taskManager = applicationContext.getBean(TaskManager.class);
    taskManager.destroy();
  }
}
